<template>
  <el-container>
    <el-aside width="200px" style=" border: 1px solid #eee">
      <el-tree
          :data="files"
          :props="props"
          :load="loadNode"
          @node-click="click"
          lazy>
        <template v-slot=" { node, data }">
          <div>{{ data.fileName }}</div>
        </template>
      </el-tree>
    </el-aside>
    <el-main>
      <router-view/>
    </el-main>
  </el-container>
</template>

<script>
import router from '../router'
import {getFile, getFileList} from "../api/file";

export default {
  name: "Explorer",
  data() {
    return {
      files: [],
      props: {
        label: 'fileName',
        children: [],
        isLeaf: 'isFile'
      },
    }
  },
  methods: {
    loadNode(node, resolve) {
      console.log(node.data)
      if (node.level === 0) {
        return resolve([{name: 'region'}]);
      }
      if (node.level > 1) return resolve([]);
      setTimeout(async () => {
        if (node.level === 0) {
          return resolve([{name: 'region'}]);
        }
        if (node.level > 1) return resolve([]);

        setTimeout(async () => {
          const data = await this.loadDir(node.data.path + '/' + node.data.fileName)
          resolve(data);
        }, 500);
      })
    },
    async click(data) {
      if (data.isDir) {
        return
      }
      let arry = data.fileName.split('.')
      let extName = arry[arry.length - 1]
      switch (extName) {
        case "txt":
          await this.$router.push("/Text?path="+data.path + '/' + data.fileName);
          break
        case "png":
          await this.$router.push("/Image?path="+data.path + '/' + data.fileName);
          break
        case "md":
          await this.$router.push("/Markdown?path="+data.path + '/' + data.fileName);
          break
      }
    },
    //加载目录
    async loadDir(path) {
      let res = await getFileList({path: path});
      if (res.data.code === 0) {
        return res.data.data
      } else {
        return []
      }

    }
  },
  async mounted() {
    this.files = await this.loadDir("/data")
  }
}
</script>

<style scoped>
.main {
}
</style>